package org.csu.onlineedubackend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.dto.CourseCommentDTO;
import org.csu.onlineedubackend.dto.CourseDTO;
import org.csu.onlineedubackend.dto.CourseDetailDTO;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.CourseService;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.User;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/courses")
@Slf4j
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    // 课程发现页
    @GetMapping
    public CommonResponse<IPage<Course>> getCourses(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String level,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String sort
    ) {
        log.info("获取课程列表 - 页码: {}, 大小: {}, 级别: {}, 分类: {}, 排序: {}", page, size, level, subject, sort);
        try {
            Page<Course> pageParam = new Page<>(page, size);
            IPage<Course> courses = courseService.getCourses(pageParam, level, subject, sort);
            log.info("课程列表获取成功 - 总数: {}", courses.getTotal());
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", courses);
        } catch (Exception e) {
            log.error("获取课程列表失败: {}", e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "查询失败: " + e.getMessage());
        }
    }

    // 课程详情
    @GetMapping("/{id}")
    public CommonResponse<CourseDetailDTO> getCourseDetail(
            @PathVariable("id") Integer id,
            @RequestParam(required = false) Integer studentId
    ) {
        try {
            // 参数校验
            if (id == null) {
                return CommonResponse.createForSuccess(ResponseCode.ERROR.getCode(), "课程ID不能为空", null);
            }
            
            log.info("获取课程详情 - 课程ID: {}, 学生ID: {}", id, studentId);
            
            // 获取课程详情
            CourseDetailDTO dto = courseService.getCourseDetail(id, studentId);
            if (dto == null) {
                log.warn("课程不存在 - 课程ID: {}", id);
                return CommonResponse.createForSuccess(ResponseCode.ERROR.getCode(), "课程不存在", null);
            }
            
            // 更新课程订阅人数 - 检查原始课程数据
            try {
                Course course = courseService.getById(id);
                if (course != null) {
                    int subscriberCount = 0;
                    
                    // 如果课程中的订阅数为空或为0，尝试从订阅表直接计算
                    if (course.getSubscriberCount() == null || course.getSubscriberCount() == 0) {
                        try {
                            subscriberCount = courseMapper.countCourseSubscriptions(id);
                            if (subscriberCount > 0) {
                                // 更新数据库中的订阅人数
                                course.setSubscriberCount(subscriberCount);
                                courseService.updateById(course);
                                log.info("更新课程订阅人数 - 课程ID: {}, 订阅人数: {}", id, subscriberCount);
                                
                                // 更新DTO中的总学生数
                                dto.setTotalStudents(subscriberCount);
                            }
                        } catch (Exception e) {
                            log.error("计算课程订阅人数失败 - 课程ID: {}", id, e);
                        }
                    } else {
                        // 使用课程中已有的订阅人数
                        subscriberCount = course.getSubscriberCount();
                        dto.setTotalStudents(subscriberCount);
                    }
                }
            } catch (Exception e) {
                log.error("更新课程订阅人数失败 - 课程ID: {}", id, e);
            }
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取课程详情成功", dto);
        } catch (Exception e) {
            log.error("获取课程详情异常 - 课程ID: {}, 错误: {}", id, e.getMessage(), e);
            return CommonResponse.createForSuccess(ResponseCode.ERROR.getCode(), "获取课程详情失败: " + e.getMessage(), null);
        }
    }

    // 课程详情
    @GetMapping("/admin/{id}")
    public CommonResponse<CourseDTO> getCourseDetail(
            @PathVariable Integer id
    ) {
        CourseDTO course = courseService.getCourseInfo(id);
        if (course == null) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
        }
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", course);
    }
    
    // 获取课程评论
    @GetMapping("/{id}/comments")
    public CommonResponse<IPage<CourseCommentDTO>> getCourseComments(
            @PathVariable Integer id,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        log.info("获取课程评论 - 课程ID: {}, 页码: {}, 大小: {}", id, page, size);
        try {
            Page<CourseCommentDTO> pageParam = new Page<>(page, size);
            IPage<CourseCommentDTO> comments = courseService.getCourseComments(id, pageParam);
            log.info("课程评论获取成功 - 课程ID: {}, 评论数: {}", id, comments.getTotal());
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", comments);
        } catch (Exception e) {
            log.error("获取课程评论失败 - 课程ID: {}, 错误: {}", id, e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取评论失败: " + e.getMessage());
        }
    }
    
    // 添加课程评论
    @PostMapping("/{id}/comments")
    public CommonResponse<Boolean> addCourseComment(
            @PathVariable Integer id,
            @RequestParam Integer studentId,
            @RequestParam String content,
            HttpServletRequest request,
            @RequestParam Integer rating,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String userAvatar
            
    ) {
        log.info("添加课程评论 - 课程ID: {}, 学生ID: {}, 评分: {}, 用户名: {}", id, studentId, rating, username);
        try {
            boolean success = courseService.addCourseComment(id, studentId, content, rating, username, userAvatar);
            if (success) {
                log.info("课程评论添加成功 - 课程ID: {}, 学生ID: {}", id, studentId);
                // 日志记录
                User user = userService.getById(studentId);
                username = user != null ? user.getUsername() : null;
                String ip = request.getRemoteAddr();
                String userAgent = request.getHeader("User-Agent");
                Course course = courseService.getById(id);
                String courseTitle = course != null ? course.getTitle() : null;
                logService.recordCourseComment(studentId, username, id, courseTitle, content, rating, ip, userAgent);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "评论成功", true);
            } else {
                log.warn("课程评论添加失败 - 课程ID: {}, 学生ID: {}, 未订阅课程", id, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "评论失败，请先订阅该课程");
            }
        } catch (Exception e) {
            log.error("添加课程评论失败 - 课程ID: {}, 学生ID: {}, 错误: {}", id, studentId, e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "添加评论失败: " + e.getMessage());
        }
    }

    // 获取课程评分信息
    @GetMapping("/{id}/rating")
    public CommonResponse<Object> getCourseRating(
            @PathVariable Integer id,
            @RequestParam(required = false) Integer studentId
    ) {
        log.info("获取课程评分信息 - 课程ID: {}, 学生ID: {}", id, studentId);
        try {
            // 获取课程
            Course course = courseService.getById(id);
            if (course == null) {
                log.warn("课程不存在 - 课程ID: {}", id);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 查询评论总数和平均评分
            Long commentCount = courseService.getCourseCommentCount(id);
            Double averageRating = courseService.getCourseAverageRating(id);
            
            // 构建返回数据
            java.util.Map<String, Object> result = new java.util.HashMap<>();
            result.put("totalComments", commentCount);
            result.put("averageRating", averageRating != null ? averageRating : 0.0);
            
            log.info("课程评分信息获取成功 - 课程ID: {}, 评论数: {}, 平均评分: {}", 
                    id, commentCount, averageRating);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", result);
        } catch (Exception e) {
            log.error("获取课程评分信息失败 - 课程ID: {}, 错误: {}", id, e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取评分信息失败: " + e.getMessage());
        }
    }

}